package pl.grabar.clinic.core.restful;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.ws.rs.core.MediaType;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import pl.grabar.clinic.core.domain.visit.Visit;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

public class RestfulClient {
	
	private static final Log LOG = LogFactory.getLog(RestfulClient.class);
	private final static String CENTRAL_URL = "http://localhost:8080/CentralGBS-web/";

	public List<Visit> getPatientRecordFromCentral(String pesel) {
		List<Visit> visits = null;

		try {
			Client client = Client.create();
//			WebResource webResource = client.resource(CENTRAL_URL + "");
			WebResource webResource = client.resource("http://localhost:8084/GrabarClinic/rest/visit/getVisits");
			
			ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
			if (response.getStatus() != 200) {
				LOG.error(response.toString() + " Akcja pobrania karty pacjenta nie udana");
				throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
			}

//			String output = response.getEntity(String.class);
//			System.out.println("Output from Server .... \n");
//			System.out.println(output);
			
			Visit[] output = response.getEntity(Visit[].class);
			
			if (output != null) {
				visits = Arrays.asList(output);
			}
			System.out.println(new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(visits));
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return visits;
	}

	public List<Visit> getPatientRecordFromCentralBase(String pesel) {
		List<Visit> visits = new ArrayList<>();

		try {
			Client client = Client.create();
			WebResource webResource = client.resource(CENTRAL_URL + "");
			ClientResponse response = webResource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class);
			
			if (response.getStatus() != 200) {
				LOG.error(response.toString() + ". Akcja pobrania karty pacjenta nie udana");
				throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
			}

			Visit[] output = response.getEntity(Visit[].class);
			
			if (output != null) {
				visits = Arrays.asList(output);
			}
			
//			String output = response.getEntity(String.class);
			System.out.println(new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(output));
		} catch (Exception e) {
			LOG.error(e.getMessage());
			e.printStackTrace();
		} finally {
			visits = null;
		}
		
		return visits;
	}
	
}
